#include "vtor_snake.h"
#include "vtor_game.h"

#ifdef __VTOR_SNAKE__


void VtorSnake_CreateFood(VtorSnake* snake)
{
	int16_t x = snake->food[0].x;
	int16_t y = snake->food[0].y;
	do
	{
		x = rand() % snake->map->width;
		y = rand() % snake->map->height;
	}while(VtorMap_GetElement(snake->map, x, y) != VtorSnake_NULL);
	// 记录食物的坐标
	snake->food[0].x = x;
	snake->food[0].y = y;
}

// 异步调用
void VtorSnake_SetSpeed(VtorSnake* snake, int8_t x, int8_t y)
{
	snake->spd.x = x;
	snake->spd.y = y;
}

void VtorSnake_Move(VtorSnake* snake)
{
	int16_t headX = snake->body[snake->headIdx].x;
	int16_t headY = snake->body[snake->headIdx].y;
	headX = headX + snake->spd.x + snake->map->width;
	headY = headY + snake->spd.y + snake->map->height;

	snake->headIdx = (snake->headIdx + 1) % snake->maxLen;
	snake->body[snake->headIdx].x = headX % snake->map->width;
	snake->body[snake->headIdx].y = headY % snake->map->height;
}

void VtorSnake_Draw(VtorSnake* snake)
{
	// 情况，然后绘制// 多线程情况下需要加锁
	VtorMap_Fill(snake->map, VtorSnake_NULL);
	for(int i = 0; i < snake->len; i++)
	{
		int16_t bodyIdx = (snake->headIdx + snake->maxLen - i) % snake->maxLen;
		int16_t x = snake->body[bodyIdx].x;
		int16_t y = snake->body[bodyIdx].y;
		VtorMap_SetElement(snake->map, x, y, VtorSnake_SNAKE);
	}
	int16_t x = snake->food[0].x;
	int16_t y = snake->food[0].y;
	VtorMap_SetElement(snake->map, x, y, VtorSnake_FOOD);

	VtorMap_Draw(snake->map);
}

int8_t VtorSnake_CheckHead(VtorSnake* snake)
{
	int16_t headX = snake->body[snake->headIdx].x;
	int16_t headY = snake->body[snake->headIdx].y;
	
	switch(VtorMap_GetElement(snake->map, headX, headY))
	{
	case VtorSnake_NULL:
		break;
	case VtorSnake_SNAKE:
		break;
	case VtorSnake_FOOD:
	{
		snake->len++;
		VtorSnake_CreateFood(snake);
		break;
	}
	}
	return 1;			//前进成功
}

// 主线程定时绘制
void VtorSnake_Play(VtorSnake* snake)
{
	//while(1)	//主循环
	{
		VtorSnake_Move(snake);
		VtorSnake_CheckHead(snake);

		// 根据情况，异步线程将地图绘制到屏幕
		// VtorSnake_Draw(snake);
		// 根据情况延时
		//Delay_ms(Game_Speed);
	}
}

#endif // __VTOR_SNAKE__

